﻿using System;

namespace FeedbackNetwork.network.loss
{
    public class CrossEntropy : Loss
    {
        public override FloatTensor GetLoss(FloatTensor predict, FloatTensor real)
        {
            float[] predict_data = predict.GetData();
            float[] real_data =real.GetData();
            int batch = predict.GetDimensionShape(0);
            int length = predict_data.Length/batch;

            FloatTensor result = new FloatTensor(new int[] { batch, 1 }, 0f);
            for(int j = 0; j < batch; j++)
            {
                float loss = 0f;
                for (int i = 0; i < length; i++)
                {
                    float y_real = real.GetData(new int[] { j, i });
                    float y_predict = predict.GetData(new int[] { j, i });
                    loss += y_real * (float)Math.Log(y_predict);
                    loss += (1 - y_real) * (float)Math.Log(1 - y_predict);
                }
                result.SetData(-loss, new int[] { j, 0 });
            }
            return result;
        }


        public override FloatTensor[] Delta(FloatTensor predict, FloatTensor real)
        {
            FloatTensor result = predict.Add(real.Mul(-1f));
            throw new NotImplementedException();
        }
    }
}
